<?php

class TransferController extends TController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	public function __construct($id, $module = null)
	{
		parent::__construct($id, $module);
		//权限审核

		//echo Yii::app()->request->pathInfo;
		//print_r(Yii::app()->params['transferRights']);
		if(!in_array(Yii::app()->request->pathInfo, Yii::app()->params['transferRights']))
		{

		}
	}

	public function init()
	{
		$this->userInfo = Yii::app()->session['userInfo'];
	}


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','inbox','start','my','test','detail','create','edit','GetDepartmentChildren','audited' ,'mailTest','welcome'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update','index'),
				'expression'=>array($this,'_isTransferManager'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}


	public function actionIndex()
	{
		$condition = '';
		if(isset($_GET['search']))
		{
			//print_r($_GET);
			$condition = " 1=1 ";
			if($_GET['search']['s_username'])
			{
				$condition .= " AND transfer_c_usernames LIKE '%".urldecode($_GET['search']['s_username'])."%' ";
			} 
			if($_GET['search']['s_status'])
			{
				$condition .= "AND status = '".$_GET['search']['s_status']."' ";
			}
			if($_GET['search']['s_o_d'])
			{
				$condition .= "AND from_department_id = '".$_GET['search']['s_o_d']."' ";
			}
			if($_GET['search']['s_n_d'])
			{
				$condition .= "AND to_department_id = '".$_GET['search']['s_n_d']."' ";
			}
			if($_GET['search']['s_t_start'] && $_GET['search']['s_t_end'])
			{
				$condition .= "AND effective_time <= '".strtotime($_GET['search']['s_t_end'])."' AND effective_time >=  '".strtotime($_GET['search']['s_t_start'])."'" ;
			}
		}
		//echo $condition;
		$serch = isset($_GET['search'])?$_GET['search']:array();

		
		$dataProvider = new CActiveDataProvider('Transfer',array(
			'criteria'=>array(
				'order' => 'id DESC',
				'condition' => $condition
				),
			'pagination'=>array(
		        'pageSize'=>20,
		    	),
			)
		); 

		//生成搜索表单
		//部门
		$ud = UserDepartment::model()->findAllByAttributes(array('status'=>1));
		//状态

		$this->render('index',array(
			'dataProvider'=>$dataProvider,'ud'=>$ud,'statusName'=>Tinit::statusName(),'search'=>$serch,
		));
	}


	public function actionInbox()
	{
		$dataProvider = new CActiveDataProvider('Transfer',array(
			'criteria'=>array(
				'condition'=>'next_unique_id="'.$this->userInfo->unique_id.'"  AND status>-2 ',
				'order' => 'id DESC',
				),
			'pagination'=>array(
		        'pageSize'=>20,
		    	),
			)
		); 
		$this->render('inbox',array(
			'dataProvider'=>$dataProvider,
		));
	}

	public function actionStart()
	{
		$dataProvider = new CActiveDataProvider('Transfer',array(
			'criteria'=>array(
				'condition'=>'start_unique_id="'.$this->userInfo->unique_id.'" AND status>-2 ORDER BY id DESC'
				),
			'pagination'=>array(
		        'pageSize'=>20,
		    	),
			)
		);
		$this->render('start',array(
			'dataProvider'=>$dataProvider,'statusName'=>Tinit::statusName(),
		));
	}

	public function actionMy()
	{

		$dataProvider = new CActiveDataProvider('Transfer',array(
			'criteria'=>array(
				'condition'=>"transfer_unique_ids like '%".$this->userInfo->unique_id."%' AND status=2 ORDER BY id DESC"
				),
			'pagination'=>array(
		        'pageSize'=>20,
		    	),
			)
		); 
		$this->render('my',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionDetail()
	{
		$model = new Transfer;
		$data = $model->getTransferDetails((int)$_GET['id']);
		if(!$model->detailCheck($data,$this->userInfo->unique_id))
		{

		}
		//print_r($data);
		$this->render('detail',array(
			'data'=>$data,
		));
	}


	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionMailTest()
	{
		$model = new Transfer;
		$transferHtml = $model->getTransferMail((int)$_GET['id']);
		header("Content-type: text/html; charset=utf-8");
		echo $transferHtml;
		die;
		
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		//print_r($_SESSION);
		if(Yii::app()->session['userGroup']['transfer'] == 1) {
			$this->welcome();
			die;
		}
		$error = 0;
		$departmentModel = new UserDepartment;
		$transferProcessModel = new TransferProcess;
		$hecUserModel = new HecUser;
		//获取当前用户的部门
		$ud = $departmentModel->findAllByAttributes(array('manager_unique_id' => $this->userInfo->unique_id,'status'=>1));
		//查看是不是hr start
		$hrOptionModel = new HrOption();
		///$transferHrStart = $hrOptionModel->findByAttributes(array('option_name'=>'transfer_hr_start'));
		//if($transferHrStart->option_value == $this->userInfo->unique_id) {
		if(Yii::app()->session['userGroup']['transfer'] >= 3) 
		{
			$ud = $departmentModel->findAllByAttributes(array('status'=>1));
			$hrStart = 1;
		} 
		else if(Yii::app()->session['userGroup']['transfer'] == 2)
		{
			//获取当前用户的部门
			$ud = $departmentModel->findAllByAttributes(array('manager_unique_id' => $this->userInfo->unique_id,'status'=>1));
			$hrStart = 0;
		}

		if(!$ud)
		{
			//echo 'no access!';
			//die;
		}
/*
		//部门数组
		$udArray = array();

		foreach ($ud as $key => $value) {
			# code...
			
			//echo $value->name;
			if($value->display == 0) {
				//获取上一级部门id
				$t = $departmentModel->findByPk($value->parent_id);
				$udArray[$key]['name'] = $t->name;
				$udArray[$key]['id'] = $t->id;
			} else {
				$udArray[$key]['name'] = $value->name;
				$udArray[$key]['id'] = $value->id;
			}
		}
		//print_r($udArray);
*/
		$model=new Transfer();
		$userDepartmentModel = new UserDepartment();
		$firstLevel = $userDepartmentModel->findAllByAttributes(array('parent_id' => 0));
		if(Yii::app()->request->isPostRequest)
		{
			//表单验证
			if($_POST['form_note'] == '')
			{
				$error = 1;
			} 
			else if((int)$_POST['form_new_department'] == 0) 
			{
				$error = 2;
			} 
			else if($_POST['transfer_uids'] == '') 
			{
				$error = 3;
			}
			else if($_POST['effective_time'] == '')
			{
				$error = 4;
			}
			if($error != 0)
			{
				$this->render('create',array(
					'model'=>$model,
					'ud' => $ud,
					'firstLevel' => $firstLevel,
					'error' => $error,
					'post' => $_POST
				));
				Yii::app()->end();
			}
			$process = $this->_getTransferProcess((int)$_POST['form_old_department'],(int)$_POST['form_new_department']);
			$model->start_unique_id = $this->userInfo->unique_id;
			$model->start_c_username = $this->userInfo->c_username;
			$model->start_username = $this->userInfo->username;
			$model->from_department_id = $_POST['form_old_department'];
			$temp = $departmentModel->findByPk((int)$_POST['form_old_department']);
			$model->from_department_name = $temp->name;
			$model->to_department_id = $_POST['form_new_department'];
			$temp = $departmentModel->findByPk((int)$_POST['form_new_department']);
			$model->to_department_name = $temp->name;
			$model->note = $_POST['form_note'];
			$model->dateline = $_SERVER['REQUEST_TIME'];
			$model->create_time = $_SERVER['REQUEST_TIME'];
			$model->effective_time = strtotime($_POST['effective_time']);
			$model->save();
			unset($temp);
			$lastInsertId = $model->id;
			//保存 transfer user
			$uids = explode(',', $_POST['transfer_uids']);
			if(!empty($uids))
			{
				$transfer_unique_ids = '';
				$transfer_c_usernames = '';
				$transfer_usernames = '';
				foreach ($uids as  $value)
				{
					$transferUserModel = new TransferUser;
					//获取user info
					$m = $hecUserModel-> findByAttributes(array('unique_id' => $value));
					$transferUserModel->transfer_id = $lastInsertId;
					$transferUserModel->username = $m->username;
					$transferUserModel->c_username = $m->c_username;
					$transferUserModel->unique_id = $value;
					$transferUserModel->entry_point = $m->entry_point;
					$transferUserModel->position = $m->position;
					$userPositionLevelModel = new UserPositionLevel;
					$l = $userPositionLevelModel->getByUniqueId($value);
					//print_r($l);
					//die;
					if($l)
					{
						$transferUserModel->old_attr_id = $l->attr_id;
						$transferUserModel->old_L = $l->attr_L_id;
						$transferUserModel->old_M = $l->attr_M_id;
						$transferUserModel->old_B = $l->B;
					}
					$transfer_unique_ids .= $value.',';
					$transfer_usernames .= $m->username.',';
					$transfer_c_usernames .= $m->c_username.',';
					$transferUserModel->save();
				}
			}
			//var_dump( $model->getErrors());
			//存入流程
			//print_r($process);
			//die;
			$transferProcessModel->saveProcess($lastInsertId , $process);
			//更新主表 next
			$model->id = $lastInsertId;
			$model->status = 1;
			//发起时 调过自己
			if($process[0]['manager_unique_id'] == $this->userInfo->unique_id)
			{
				$p = $process[1];
				$model->t_index = 2;
			}
			else 
			{
				$p = $process[0];
				$model->t_index = 1;
			}
			//$model->t_index = 2;
			$model->next_unique_id = $p['manager_unique_id'];
			$nextUser = $hecUserModel->findByAttributes(array('unique_id'=>$p['manager_unique_id']));
			$model->next_username = $nextUser->username;
			$model->next_c_username = $nextUser->c_username;
			$model->transfer_usernames = $transfer_usernames;
			$model->transfer_unique_ids = $transfer_unique_ids;
			$model->transfer_c_usernames = $transfer_c_usernames;
			$model->save();
			//保存transfer index
			$transferIndexModel = new TransferIndex;
			$transferIndexModel->transfer_id = $lastInsertId;
			$transferIndexModel->action_unique_id = $this->userInfo->unique_id;
			$transferIndexModel->action_type = 1;
			$transferIndexModel->t_index = 0;
			$transferIndexModel->dateline = $_SERVER['REQUEST_TIME'];
			$transferIndexModel->save();
			//发送邮件
			TSendMail::send($this->userInfo , $model  ,'');
			//die;
			$this->showAlert(array('type'=>'1','content'=>'发起成功！','url'=>'transfer/start'));
		//} catch (Exception $e) {
		//	$this->showAlert(array('type'=>'2','content'=>'发起出错！！！','url'=>'transfer/create'));
		//}
		}
		//print_r($ud);
		$this->render('create',array(
			'model'=>$model,
			'ud' => $ud,
			'firstLevel' => $firstLevel,
			'error' => $error
		));
		Yii::app()->end();
	}


	/**
	 * 
	 */
	public function actionEdit()
	{
		$id = $_POST['id'] ? (int)$_POST['id'] : (int)$_GET['id'];
		$model = new Transfer;
		$data = $model->getTransferDetails($id);
		if(!$model->editCheck($data,$this->userInfo->unique_id))
		{

		}
		if(Yii::app()->request->isPostRequest)
		{
			print_r($_POST);
			die;
			$model=$model->findByPk($id);
			$model->status = $_POST['status'];
			if($model->update())
			{
				$transferIndexModel = new TransferIndex;
				$transferIndexModel->transfer_id = $id;
				$transferIndexModel->action_unique_id = $this->userInfo->unique_id;
				$transferIndexModel->action_type = -2;
				$transferIndexModel->dateline = $_SERVER['REQUEST_TIME'];
				$transferIndexModel->save();
				$this->showAlert(array('type'=>'1','content'=>'更新成功！','url'=>'transfer/edit/id/'.$id));
			}
			else 
			{
				die;
			}

		}
		$this->render('edit',array(
			'data'=>$data,
		));
	}
	


	public function actionCancel()
	{

		$this->loadModel($id)->cancel();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}

	public function actionAudited()
	{

		$dataProvider = new CActiveDataProvider('Transfer',array(
			'criteria'=>array(
				'condition'=>"audited_unique_ids like '%".$this->userInfo->unique_id."%' ORDER BY id DESC"
			),
			'pagination'=>array(
		        'pageSize'=>20,
		    	),
			)
		);
		$this->render('audited',array(
			'dataProvider'=>$dataProvider,'statusName'=>Tinit::statusName(),
		));
	}


	public function actionTest()
	{
		$this->showAlert(array('type'=>'1','content'=>'测试','url'=>'transfer/create'));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Transfer']))
		{
			$model->attributes=$_POST['Transfer'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Transfer::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='transfer-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}


	public function getTransferInfo()
	{
		$transferAuditModel = new TransferAudit;

		
	}

	/**
	*
	 */
	public function actionGetDepartmentChildren()
	{
		if($_GET)
		{
			$model = new UserDepartment();
			$data = $model->findAllByAttributes(array('parent_id' => (int)$_GET['id'],'status'=>"1"));
			$array = array();
			$array['children'] = array();
			$i = 0;
			foreach ($data as $value){
				$array['children'][$i]['id'] = $value->id;
				$array['children'][$i]['name'] = $value->name;
				$array['children'][$i]['manager_unique_id'] = $value->manager_unique_id;
				$i++;
			}
			$hrOptionModel = new HrOption();
			$transferHrStart = $hrOptionModel->findByAttributes(array('option_name'=>'transfer_hr_start'));
			if($transferHrStart->option_value == $this->userInfo->unique_id) 
				$hrStart = 1;
			else
				$hrStart = 0;

			$artFlag = 0;
			if($_GET['uids'])
			{
				$uidsArray = explode(',', $_GET['uids']);
				$artFlag = HecUser::model()->checkArt($uidsArray);
			}
			$artFlag = $artFlag==1 ? $artFlag : 0;
			$temp = $this->_getTransferProcess((int)$_GET['oid'],(int)$_GET['id'],1,$artFlag);
			$hecUserModel = new HecUser;
			$array['process'] = array();
			//print_r($temp);
			foreach ($temp as  $value)
			{
				$m = $hecUserModel-> findByAttributes(array('unique_id' => $value['manager_unique_id']));
				array_push($array['process'], $m->c_username);
			}
			Tools::returnJson(0,$array);
			Yii::app()->end();
		}
	}



	private function _getTransferProcess($oldId,$newId,$hrStart=0,$artFlag = 0)
	{
		$departmentModel = new UserDepartment;
		$transferProcessModel = new TransferProcess;
		$departmentModel->departmentPath = array();
		//旧部门流程
		if($oldId != 0)
		{
			$departmentModel->getPath($oldId);
			$oldProcess = $departmentModel->departmentPath;
			$departmentModel->departmentPath = array();
		}
		//print_r($oldProcess);
		//新部门流程
		if($newId != 0)
		{
			$departmentModel->getPath($newId);
			$newProcess = $departmentModel->departmentPath;
			$departmentModel->departmentPath = array();
		}
		//print_r($newProcess);
		//分析流程
		return $transferProcessModel->formatProcess($oldProcess,$newProcess,$hrStart,$artFlag);
	}


	protected function _isTransferManager()
	{
		return Yii::app()->session['userGroup']['transfer']>=2?1:0;
	}


	public function welcome()
	{
		$array = array('C120650'=>'Mobile Game/技术支持','C130797'=>'Social Game/商业智能','C120681'=>'Back Office/Game Distribution/美术共享中心','C110230'=>'Hardcore Game');

		$adminAssistant = array();
		foreach ($array as $key => $value) 
		{
			$adminAssistant[$key]['user_info'] = HecUser::model()->findByAttributes(array('unique_id'=>$key));
			$adminAssistant[$key]['department'] = $value;
		}

		$this->render('welcome',array(
			'adminAssistant'=>$adminAssistant
		));
	}

	public function actionWelcome()
	{
		$array = array('C120650'=>'Mobile Game/技术支持','C130797'=>'Social Game/商业智能','C120681'=>'Back Office/Game Distribution/美术共享中心','C110230'=>'Hardcore Game');

		$adminAssistant = array();
		foreach ($array as $key => $value) 
		{
			$adminAssistant[$key]['user_info'] = HecUser::model()->findByAttributes(array('unique_id'=>$key));
			$adminAssistant[$key]['department'] = $value;
		}

		$this->render('welcome',array(
			'adminAssistant'=>$adminAssistant
		));
	}




}
